<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div class="time-graph">
    <canvas style="margin-top: -20px" id="time-graph-canvas" width="160" height="160"></canvas>
  </div>
  <script>
    function drawMain(drawing_elem, percent, forecolor, bgcolor)
    {
      /*  
          函数封装：
          @drawing_elem: 绘制对象
          @percent：绘制圆环百分比, 范围[0, n]
          @forecolor: 绘制圆环的前景色，颜色代码
          @bgcolor: 绘制圆环的背景色，颜色代码
      */
      var context = drawing_elem.getContext("2d");
      var center_x = drawing_elem.width / 2;
      var center_y = drawing_elem.height / 2;
      var rad = Math.PI * 2 / 1500; //Math.PI = 180°,此处是吧360°分成1500份
      var speed = 0;

      // 绘制背景圆圈
      function backgroundCircle()
      {
        context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
        context.beginPath();
        context.lineWidth = 8; //设置线宽
        var radius = center_x - context.lineWidth; //圆角
        context.lineCap = "round";
        context.strokeStyle = bgcolor;
        context.arc(center_x, center_y, radius, Math.PI / 1.3333, Math.PI / 4, false); //用于绘制圆弧context.arc(x坐标，y坐标，半径，起始角度，结束角度，逆时针还是顺时针绘图：False = 顺时针、true = 逆时针)。
        context.stroke();
        context.closePath();
        context.restore();
      }

      // 绘制运动圆环
      function foregroundCircle(n)
      {
        context.save();
        context.strokeStyle = forecolor;
        context.lineWidth = 8;
        context.lineCap = "round";
        var radius = center_x - context.lineWidth;
        context.beginPath();
        context.arc(center_x, center_y, radius, Math.PI / 1.3333, Math.PI / 1.3333 + n * rad, false); //用于绘制圆弧context.arc(x坐标，y坐标，半径，起始角度，终止角度，顺时针/逆时针)
        context.stroke();
        context.closePath();
        context.restore();
      }

      //绘制文字
      function text(n)
      {
        context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
        context.fillStyle = forecolor;
        context.textAlign = 'center';
        var font_size = 40;
        context.font = font_size + "px Helvetica";
        context.fillText(n.toFixed(0), center_x, center_y + font_size / 2); // 在画布上写文本fillText(内容，x坐标，y坐标)，
        context.restore();
      }

      //执行动画
      (function drawFrame()
      {
        window.requestAnimationFrame(drawFrame);
        context.clearRect(0, 0, drawing_elem.width, drawing_elem.height);
        backgroundCircle();
        text(speed);
        foregroundCircle(speed);
        if (speed >= percent) return;
        speed += 10; //文字变化速度
      }());
    }
    // 调用函数：
    var time_canvas = document.getElementById("time-graph-canvas"); /*获取canvas容器*/
    this.drawMain(time_canvas, 750, "#85d824", "#eef7e4");
  </script>
</body>

</html>